﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.SharePoint;

namespace Mystery.SharePoint
{
	/// <summary>
	/// Encapulates extended metadata about a site
	/// </summary>
	public class SiteMetadata
	{
		private const string OwnerKey = "SPM.Owner";
		private SPWeb _web;
		/// <summary>
		/// Gets the owner of the web
		/// </summary>
		public string Owner { get; set; }
		/// <summary>
		/// Metadata constructur
		/// </summary>
		/// <param name="site">The site whose metadata we are manipulating</param>
		public SiteMetadata(SPSite site)
		{
			_web = site.RootWeb;
			this.Owner = this.Read(OwnerKey, "");
		}
		/// <summary>
		/// Updates the metadata back to it's store
		/// </summary>
		public void Update()
		{
			if (this.TransferValues() == true)
			{
				this.Commit();
			}
		}
		/// <summary>
		/// Transfers the values from the properties to the actual storage structure
		/// </summary>
		/// <returns>Return true if storage structure must be updated, false if no changes</returns>
		protected virtual bool TransferValues()
		{
			return this.Write(OwnerKey, this.Owner);
		}
		/// <summary>
		/// Reads a value from the storage structure. Override this if you want to use something
		/// different from the property bag
		/// </summary>
		/// <param name="key">Key of the value being read</param>
		/// <param name="defaultValue">Default value to use if nothing has been set</param>
		/// <returns>Value from storage structure or default value provided.</returns>
		protected virtual string Read(string key, string defaultValue)
		{
			return _web.Properties.Read(key, defaultValue);
		}
		/// <summary>
		/// Writes a value to the storage structure. Override this if you want to use something
		/// different from the property bag
		/// </summary>
		/// <param name="key">Key of value being written</param>
		/// <param name="value">Value to be written</param>
		/// <returns>True if the storeage structure was updated.</returns>
		protected virtual bool Write(string key, object value)
		{
			return _web.Properties.Write(key, value);
		}
		/// <summary>
		/// Commits changes made to the storage structure. Override this if you want to use something
		/// different from the property bag
		/// </summary>
		protected virtual void Commit()
		{
			_web.Properties.Update();
		}
	}
}
